package pcloud.server.datastore;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

import pcloud.server.Logger;

public class PropertyFileTaskList implements ClientTaskList
{
	private String clientId;
	private Properties tasks = null;
	private String tasklistFilePath;

	public PropertyFileTaskList(String id, String datastoreRootPath)
	{
		clientId = id;
		tasklistFilePath = datastoreRootPath + "/"+clientId+".properties";
	}

	/* (non-Javadoc)
	 * @see pcloud.server.datastore.ClientTaskList#updateTask(java.lang.String, java.lang.String)
	 */
	@Override
	public boolean updateTask(String path, String action)
	{
		try {
//			path = path.replace(" ", "\\ ");
			tasks.setProperty(path, action);
			Logger.log("\tbefore save task path:"+path+", action: "+action);
			
			saveTasks();
		} catch (IOException e) {
			Logger.log("\tafter save task return: false");
			return false;
		}
		Logger.log("\tafter save task return: true");
		return true;
	}

	private void saveTasks() throws IOException
	{
		File taskFile = new File(tasklistFilePath);
		taskFile.createNewFile();
		
		Logger.log("\tUpdate task file: ["+taskFile.getName()+"], action");
		BufferedWriter writer = new BufferedWriter( new FileWriter(taskFile) );
		tasks.store(writer, "update");
		writer.close();
	}

	private Properties getTasks()
	{
		if (tasks != null) {
			return tasks;
		}
		
		tasks = new Properties();
		
		File tasklistFile = new File(tasklistFilePath);
		if (!tasklistFile.exists()) {
			return tasks;
		}
		try {
			BufferedReader reader = new BufferedReader(new FileReader(tasklistFile));
			tasks.load(reader);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tasks;
	}

	/* (non-Javadoc)
	 * @see pcloud.server.datastore.ClientTaskList#removeTask(java.lang.String, java.lang.String)
	 */
	@Override
	public boolean removeTask(String path, String action)
	{
		Logger.log("\tremove task, path:"+path+", action:"+action);
		getTasks().remove(path);
		try {
			saveTasks();
		} catch (IOException e) {
			Logger.log("\tafter save task return: false");
			return false;
		}
		Logger.log("\tafter save task return: true");
		return true;
	}

	/* (non-Javadoc)
	 * @see pcloud.server.datastore.ClientTaskList#size()
	 */
	@Override
	public int size()
	{
		return getTasks().size();
	}
}
